using System;
using System.Net.Sockets;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
using System.Net;
using XcoAppSpaces.Transport.Sockets.Auth.Contract.DoServerHandshake;

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	class SendChallenge : ISendChallenge
	{
		private int challengeLength;
		private readonly Random random = new Random();

		public void In_Connection(ConnectionInfo conn)
		{
			//Console.WriteLine("SendChallenge.In_Connection");
			try
			{
				var challenge = GenerateChallenge();
				conn.Stream.Write(challenge, 0, challenge.Length);
				Out_ValidConnection(new ConnectionWithChallenge { Connection = conn, Challenge = challenge });
			}
			catch
			{
				Out_InvalidConnection(conn.Client);
			}
		}

		public event ValidChallengeConnectionHandler Out_ValidConnection;

        public event TcpClientHandler Out_InvalidConnection;

		public void Inject(SecuritySettings securitySettings)
		{
			challengeLength = securitySettings.ChallengeLength;
		}

		private byte[] GenerateChallenge()
		{
			var bytes = new byte[challengeLength];
			random.NextBytes(bytes);
			return bytes;
		}
	}
}
